package com.heima.comment.service.Impl;

import com.heima.comment.service.CommentRepayService;
import com.heima.feign.user.IUserFeignClient;
import com.heima.model.comment.dtos.CommentRepayLikesDto;
import com.heima.model.comment.dtos.CommentRepayPageDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.pojos.CommentRepay;
import com.heima.model.comment.vos.CommentRepayVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IUserFeignClient iUserFeignClient;

    /**
     * 文章评论回复保存
     *
     * @param commentSaveDto
     * @return
     */
    @Override
    public ResponseResult commentSave(CommentRepaySaveDto commentSaveDto) {

        //校验：
        if (commentSaveDto.getCommentId() == null) {
            //评论Id不存在
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "当前评论不存在、");
        }

        //判断当前评论用户是否登录：
        ApUser user = ApThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH, "请先登录。");
        }

        //根据当前线程中的userId查询对应的姓名：
        ApUser userById = iUserFeignClient.findUserById(user.getId());
        String userName = userById.getName();

        //封装数据
        CommentRepay commentRepay = new CommentRepay();
        commentRepay.setCommentId(commentSaveDto.getCommentId());
        commentRepay.setContent(commentSaveDto.getContent());
        commentRepay.setAuthorId(user.getId());
        commentRepay.setAuthorName(userName);
        commentRepay.setCreatedTime(new Date());
        commentRepay.setLikes(0);
        commentRepay.setUpdatedTime(new Date());

        //保存到MongoDB
        mongoTemplate.save(commentRepay);

        //将回复评论数量回显 +1
        ApComment apComment = mongoTemplate.findById(commentSaveDto.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply() + 1);
        mongoTemplate.save(apComment);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    /**
     * 查询评论回复列表：
     *
     * @param commentPageDto
     * @return
     */
    @Override
    public ResponseResult commentPage(CommentRepayPageDto commentPageDto) {
        //校验参数：
        if (commentPageDto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //参数健壮：
//        if (commentPageDto.getMinDate() == null) {
//            commentPageDto.setMinDate(new Date());
//        }
//        if (commentPageDto.getSize() == null || commentPageDto.getSize() < 0) {
//            commentPageDto.setSize(10);
//        } else {
//            commentPageDto.setSize(Math.min(10, commentPageDto.getSize()));
//        }
        int size = 10;

        //构建查询条件：
        Query query = Query.query(Criteria.where("createdTime").lte(commentPageDto.getMinDate())
                .and("commentId").is(commentPageDto.getCommentId()));
        //分页查询：倒叙排序
        query.with(Sort.by(Sort.Direction.DESC, "createdTime"))
                .limit(size);//commentPageDto.getSize());

        List<CommentRepay> commentRepayList = mongoTemplate.find(query, CommentRepay.class);


        //3.数据封装返回
        //3.1 用户未登录
        ApUser user = ApThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.okResult(commentRepayList);
        }


        //需要查询当前评论中哪些数据被点赞了
        List<String> idList = commentRepayList.stream().map(x ->
                x.getId()).collect(Collectors.toList());
        Query query1 = Query.query(Criteria.where("commentRepayId").in(idList)
                .and("authorId").is(user.getId()));
        List<ApCommentLike> apCommentRepayLikes = mongoTemplate.find(query1, ApCommentLike.class);
        if (apCommentRepayLikes == null || apCommentRepayLikes.size() == 0) {
            return ResponseResult.okResult(commentRepayList);
        }

        List<CommentRepayVo> resultList = new ArrayList<>();
        commentRepayList.forEach(x -> {
            CommentRepayVo vo = new CommentRepayVo();
            BeanUtils.copyProperties(x, vo);
            for (ApCommentLike apCommentLike : apCommentRepayLikes) {
                if (x.getId().equals(apCommentLike.getCommentId())) {
                    vo.setOperation((short) 0);
                    break;
                }
            }
            resultList.add(vo);
        });

        return ResponseResult.okResult(resultList);

    }


    /**
     * 评论回复点赞
     *
     * @param commentLikesDto
     * @return
     */
    @Override
    public ResponseResult commentLikes(CommentRepayLikesDto commentLikesDto) {
        //参数校验：
        if (commentLikesDto.getCommentRepayId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论不存在");
        }

        //2.判断是否登录
        ApUser user = ApThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }


        //根据ID查询数据
        CommentRepay commentRepay = mongoTemplate.findById(commentLikesDto.getCommentRepayId(), CommentRepay.class);

        //点赞操作：
        if (commentRepay != null && commentLikesDto.getOperation() == 0) {
            //跟新点赞数量:
            commentRepay.setLikes(commentRepay.getLikes() + 1);
            mongoTemplate.save(commentRepay);

            //保存评论点赞数据
            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setCommentId(commentRepay.getId());
            apCommentLike.setAuthorId(user.getId());
            mongoTemplate.save(apCommentLike);

        } else {
            //更新评论点赞数量
            int tmp = commentRepay.getLikes() - 1;
            tmp = tmp < 1 ? 0 : tmp;
            commentRepay.setLikes(tmp);
            mongoTemplate.save(commentRepay);

            //删除评论点赞
            Query query = Query.query(Criteria.where("commentRepayId").is(commentRepay.getId()).and("authorId").is(user.getId()));
            mongoTemplate.remove(query, ApCommentLike.class);
        }

        //4.取消点赞
        Map<String, Object> result = new HashMap<>();
        result.put("likes", commentRepay.getLikes());
        return ResponseResult.okResult(result);
    }

//    /**
//     * 点赞取消点赞更新MongoDB
//     * @param commentLikesDto
//     * @param state
//     */
//    private void likeOrUnLike(CommentRepayLikesDto commentLikesDto, Short state) {
//
//        //创建查询条件：
//        Query query = Query.query(Criteria.where("commentId").is(commentLikesDto.getCommentRepayId()));
//        //修改：
//        CommentRepay commentRepay = mongoTemplate.findOne(query, CommentRepay.class);
//        commentRepay.setLikes(commentRepay.getLikes() + state);
//        //更新MongoDB
//        mongoTemplate.save(commentRepay);
//    }

}